package com.situ.onlinebookstore.back.controller;


import com.situ.onlinebookstore.back.service.AdminService;
import com.situ.onlinebookstore.common.entity.Admin;
import com.situ.onlinebookstore.common.vo.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController //相当于@Controller与@ResponseBody合并
//@Controller
@RequestMapping("/admin")
@RequiredArgsConstructor
//@ResponseBody //当前controller中的每一个处理器都是返回json数据的
public class AdminController {
    private final AdminService adminService;

    @RequestMapping("/login")
    public Result login(Admin admin, String verCode, HttpSession session, Boolean remember, HttpServletResponse response) {
        //1-获取参数
        try {
            //2-参数的验证
            String sessionVerCode = (String) session.getAttribute("verCode");
            if (sessionVerCode == null || !sessionVerCode.equalsIgnoreCase(verCode)) {
                //如果Session并没有验证码，或者是和用户输入的不一样
                throw new Exception("验证码错误！");
            }
            //格式
            if (!admin.getUsername().matches("^[a-zA-Z0-9]{3,16}$")) {
                throw new Exception("账号格式错误！");
            }
            if (!admin.getPassword().matches("^[a-zA-Z0-9]{3,16}$")) {
                throw new Exception("密码格式错误！");
            }
            //3-逻辑处理
            admin = adminService.login(admin);
            //保存登陆状态
            session.setAttribute("admin", admin);
            //处理记住密码
            if (remember != null && remember) {
                Cookie cookieUsername = new Cookie("username", admin.getUsername());
                Cookie cookiePassword = new Cookie("password", admin.getPassword());
                cookieUsername.setPath("/");
                cookiePassword.setPath("/");
                cookieUsername.setMaxAge(60 * 60 * 24 * 7);
                cookiePassword.setMaxAge(60 * 60 * 24 * 7);
                response.addCookie(cookieUsername);
                response.addCookie(cookiePassword);
            }
            //成功
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            //登陆失败
            return Result.error(e.getMessage());
        }

    }

    //获取当前登录用户信息
    @RequestMapping("/getLoginAdmin")
    public Result getLoginAdmin(HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            return Result.error("用户未登录");
        } else {
            return Result.ok(admin);
        }
    }

    //退出登录
    @RequestMapping("/logout")
    public Result logout(HttpSession session, HttpServletResponse response) {
        session.invalidate();
        //清除自动登录
        Cookie usernameCookie = new Cookie("username", "");
        Cookie passwordCookie = new Cookie("password", "");
        usernameCookie.setPath("/");
        passwordCookie.setPath("/");
        usernameCookie.setMaxAge(0);
        passwordCookie.setMaxAge(0);
        response.addCookie(usernameCookie);
        response.addCookie(passwordCookie);
        return Result.ok();
    }

    @RequestMapping("/search")
    //
    public Result search(Integer page, Integer limit, Admin admin) {
        if (page == null) {
            return Result.ok(adminService.search(admin));
        } else {
            return Result.ok(adminService.searchForPage(page, limit, admin));
        }
    }

    @RequestMapping("/edit")
    public Result edit(Admin admin) {
        //1-接收参数
        try {
            //2-参数校验
            if (admin.getPhone() != null && !admin.getPhone().matches("^1[35-9][0-9]{9}$")) {
                throw new Exception("电话格式不对！");
            }
            if (admin.getEmail() != null && !admin.getEmail().matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")) {
                throw new Exception("邮箱格式不对！");
            }

            //3-调用Service层
            adminService.edit(admin);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }

    //建号
    @RequestMapping("/add")
    public Result add(Admin admin) {
        try {
            //2-参数校验
            if (!admin.getUsername().matches("^[a-zA-Z0-9]{3,16}$")) {
                throw new Exception("账号格式错误！");
            }
            if (admin.getRealname() != null && admin.getRealname().length() > 0 && !admin.getRealname().matches("^[\\u4E00-\\u9FA5]{2,10}(·[\\u4E00-\\u9FA5]{2,10}){0,2}$")) {
                throw new Exception("姓名格式不对！");
            }
            if (admin.getPhone() != null && admin.getPhone().length() > 0 && !admin.getPhone().matches("^1[35-9][0-9]{9}$")) {
                throw new Exception("电话格式不对！");
            }
            if (admin.getEmail() != null && admin.getEmail().length() > 0 && !admin.getEmail().matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")) {
                throw new Exception("邮箱格式不对！");
            }
            //默认密码123
            admin.setPassword("123");

            adminService.add(admin);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }

    @RequestMapping("/reset")
    public void resetPwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1-获取参数
        String oldPwd = request.getParameter("oldPwd");
        String newPwd = request.getParameter("newPwd");
        String rePwd = request.getParameter("rePwd");
        try {
            //2-校验参数 //3-16
            if (oldPwd == null || !oldPwd.matches("^.{3,16}$")) {
                throw new Exception("旧密码格式不正确");
            }
            if (newPwd == null || !newPwd.matches("^.{3,16}$")) {
                throw new Exception("新密码格式不正确");
            }
            if (rePwd == null || !rePwd.equals(newPwd)) {
                throw new Exception("两次密码不一致");
            }

//            获取当前登录的员工,如果员工没登录
            Admin admin = (Admin) request.getSession().getAttribute("admin");
//            3-调用service
            adminService.resetPwd(oldPwd, newPwd, admin.getId());
            //修改成功
            request.getSession().invalidate();
            //返回JSON
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().append("{\"code\": 0}");

        } catch (Exception e) {
            e.printStackTrace();
            //修改失败
            //返回JSON    失败， 错误信息
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().append("{\"code\": 1, \"msg\": \"" + e.getMessage() + "\"}");
        }
    }
}
